package com.yuuko.yuukoapi.framework.extension

import com.yuuko.yuukoapi.common.request.PageParam
import org.babyfish.jimmer.spring.model.SortUtils
import org.babyfish.jimmer.spring.repository.KRepository
import org.babyfish.jimmer.spring.repository.orderBy
import org.babyfish.jimmer.sql.fetcher.Fetcher
import org.babyfish.jimmer.sql.kt.ast.query.specification.KSpecification

/**
 * 分页查询扩展
 * @param page 分页条件
 * @param specification 查询条件
 * @param fetcher 查询字段
 */
fun <E : Any, T : Any> KRepository<E, T>.findPage(
    page: PageParam,
    specification: KSpecification<E>? = null,
    fetcher: Fetcher<E>? = null,
) = sql.createQuery(entityType) {
    where(specification)
    orderBy(SortUtils.toSort(page.sort))
    select(table.fetch(fetcher))
}.fetchPage(page.page, page.pageSize)

